package com.lefu.es.blenew.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import com.lefu.es.blenew.utils.StringUtils1;
import com.lefu.es.constant.BLEConstant;
import com.lefu.es.util.LogUtil;

import java.util.List;
import java.util.UUID;


/**
 * BLE服务
 * @author andy
 * 2016-10-26
 */
@SuppressLint("NewApi")
public class BluetoothLeService extends Service {

    public static final int STATE_DISCONNECTED = 0;
    public static final int STATE_CONNECTING = 1;
    public static final int STATE_CONNECTED = 2;
    private final IBinder mBinder = new LocalBinder();
    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private String mBluetoothDeviceAddress;
    private BluetoothGatt mBluetoothGatt;
    private int mConnectionState = STATE_DISCONNECTED;

    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

        @Override
        public void onConnectionStateChange(final BluetoothGatt gatt, int status, final int newState) {
            if (status == BluetoothGatt.GATT_SUCCESS){
                if (newState == BluetoothProfile.STATE_CONNECTED) {
                    mConnectionState = STATE_CONNECTED;
                    broadcastUpdate(BLEConstant.ACTION_GATT_CONNECTED);
                    mBluetoothGatt.discoverServices();
                } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                    mConnectionState = STATE_DISCONNECTED;
                    broadcastUpdate(BLEConstant.ACTION_GATT_DISCONNECTED);
                    refreshCache(gatt);
                    gatt.disconnect();
                    gatt.close();
                }else{
                    refreshCache(gatt);
                    broadcastUpdate(BLEConstant.ACTION_GATT_DISCONNECTED);
                    gatt.disconnect();
                    gatt.close();
                    mConnectionState = STATE_DISCONNECTED;
                }
            }else{
                mConnectionState = STATE_DISCONNECTED;
                broadcastUpdate(BLEConstant.ACTION_GATT_DISCONNECTED);
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(BLEConstant.ACTION_GATT_SERVICES_DISCOVERED);
            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                gatt.getDevice().getAddress();
				/*读到数据*/
                broadcastUpdate(BLEConstant.ACTION_DATA_AVAILABLE, characteristic, gatt);
				/*释放连接*/
                disconnect();
            }
        }

        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            broadcastUpdate(BLEConstant.ACTION_DATA_AVAILABLE, characteristic, gatt);
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
        }

        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
        }
    };

    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        sendBroadcast(intent);
    }

    private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic, BluetoothGatt gatt) {
        final Intent intent = new Intent(action);
        final byte[] data = characteristic.getValue();
        intent.putExtra(BLEConstant.EXTRA_DATA, StringUtils1.bytes2HexString(data));
        if (gatt != null && gatt.getDevice() != null) {
            intent.putExtra("mac", gatt.getDevice().getAddress());
        }
        sendBroadcast(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        close();
        return super.onUnbind(intent);
    }

    public void close() {
        if (mBluetoothGatt != null) {
            mBluetoothGatt.disconnect();
            mBluetoothGatt.close();
            mBluetoothGatt = null;
        }
    }

    public boolean initialize() {
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            if (mBluetoothManager == null) {
                LogUtil.e("Unable to initialize BluetoothManager.");
                return false;
            }
        }
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            LogUtil.e("Unable to obtain a BluetoothAdapter.");
            return false;
        }
        return true;
    }

    public boolean connect(final String address) {
        final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        if (device == null) {
            return false;
        }
        mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
        LogUtil.e("*****开始连接设备**address-->" + address);
        if (mBluetoothAdapter == null || address == null) {
            return false;
        }
        if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) {
            if (mBluetoothGatt.connect()) {
                return true;
            } else {
                return false;
            }
        }
        mBluetoothDeviceAddress = address;
        mConnectionState = STATE_CONNECTING;
        return true;
    }

    public void disconnect() {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            return;
        }
        mBluetoothGatt.disconnect();
        LogUtil.e("****断开蓝牙****");
    }

    public void writeCharacteristic(BluetoothGattCharacteristic characteristic) {
        if (mBluetoothAdapter != null && mBluetoothGatt != null) {
            mBluetoothGatt.writeCharacteristic(characteristic);
        }
    }

    public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
        if (mBluetoothAdapter != null && mBluetoothGatt != null) {
            mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
                    UUID.fromString(SampleGattAttributes1.CLIENT_CHARACTERISTIC_CONFIG));
            if (descriptor != null) {
                descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                mBluetoothGatt.writeDescriptor(descriptor);
            }
        }
    }

    public void setCharacteristicIndiacate(BluetoothGattCharacteristic characteristic, boolean enabled) {
        if (mBluetoothGatt != null && null != characteristic) {
            mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
                    UUID.fromString(SampleGattAttributes1.CLIENT_CHARACTERISTIC_CONFIG));
            if (descriptor != null) {
                descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
                mBluetoothGatt.writeDescriptor(descriptor);
            }
        }
    }

    public List<BluetoothGattService> getSupportedGattServices() {
        if (mBluetoothGatt == null) {
            return null;
        }
        return mBluetoothGatt.getServices();
    }

    public BluetoothGattCharacteristic getCharacteristic(List<BluetoothGattService> gattServices, String s) {
        if (gattServices == null)
            return null;
        for (BluetoothGattService gattService : gattServices) {
            String suuid = gattService.getUuid().toString();
            if (suuid.substring(4, 8).endsWith("fff0")) {
                return gattService.getCharacteristic(UUID.fromString("0000" + s + "-0000-1000-8000-00805f9b34fb"));
            }
        }

        return null;
    }

    public BluetoothGattCharacteristic getCharacteristicNew(List<BluetoothGattService> gattServices, String s) {
        if (gattServices == null)
            return null;
        for (BluetoothGattService gattService : gattServices) {
            String suuid = gattService.getUuid().toString();
            if (suuid.substring(4, 8).endsWith("181b")) {
                return gattService.getCharacteristic(UUID.fromString("0000" + s + "-0000-1000-8000-00805f9b34fb"));
            }
        }

        return null;
    }

    public int getConnectionState() {
        return mConnectionState;
    }

    public void setConnectionState(int mConnectionState) {
        this.mConnectionState = mConnectionState;
    }

    public void refreshCache(BluetoothGatt gatt){
        if (gatt != null) {
            gatt.disconnect();
            try {
                BluetoothGatt.class.getMethod("refresh").invoke(gatt);
            } catch (Exception e) {
                e.printStackTrace();
            }
            gatt.close();
        }
    }

    public class LocalBinder extends Binder {
        public BluetoothLeService getService() {
            return BluetoothLeService.this;
        }
    }

}
